<?php

namespace plugin\ssh\app\common;

class CustomSsh
{
    protected $host;

    protected $port = 22;

    protected $password;

    protected $publicKey;

    protected $privateKey;

    protected $session;

    protected $username;

    public function __construct(array $config, $connect_type = 'password')
    {
        $this->host = $config['host'];
        $this->port = $config['port'] ?? 22;
        $this->password = $config['password'] ?? '';
        $this->publicKey = $config['publicKey'] ?? '';
        $this->privateKey = $config['privateKey'] ?? '';
        $this->username = $config['username'] ?? '';
        $this->session = ssh2_connect($this->host, $this->port);
        if ($connect_type == 'password') {
            ssh2_auth_password($this->session, $this->username, $this->password);
        } else {
            ssh2_auth_pubkey_file($this->session, $this->username, $this->publicKey, $this->privateKey);
        }
    }

    public function execute($cmd)
    {
        if ($cmd == "") {
            return false;
        }
        $stream = ssh2_exec($this->session, $cmd);

        stream_set_blocking($stream, true);

        $content = stream_get_contents($stream);

        return trim($content);
    }

    //接收文件
    public function recvFile($remote_file, $local_file)
    {
        return ssh2_scp_recv($this->session, $remote_file, $local_file);
    }

    //发送文件
    public function sendFile($local_file, $remote_file)
    {
        return ssh2_scp_send($this->session, $local_file, $remote_file);
    }

    public function __destruct()
    {
        ssh2_disconnect($this->session);
    }
}
